package com.telit.common.util;

import cn.hutool.json.JSONUtil;
import com.aliyun.sdk.service.dyvmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dyvmsapi20170525.models.SingleCallByTtsRequest;
import com.aliyun.sdk.service.dyvmsapi20170525.models.SingleCallByTtsResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.CompletableFuture;


/**
 * @author yuzhanxiang
 * @description: 语音工具类
 * @copyright 天立泰科技股份有限公司
 * @since 2022/4/1 16:31
 **/
@Component
@Slf4j
public class VoiceUtils implements ApplicationListener<ContextRefreshedEvent> {

    private static final String BEAN_NAME = "voiceClient";

    private static AsyncClient client;


    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        client = (AsyncClient) event.getApplicationContext().getBean(BEAN_NAME);
    }


    /**
     * 给手机号发电话通知
     *
     * @param mobiles      电话号码 批量
     * @param templateCode 语音模板编码
     * @param param        传入语音模板参数
     */
    public static void dialNoitce(List<String> mobiles, String templateCode, Object param) {
        final String paramJson = JSONUtil.toJsonStr(param);
        mobiles.stream().map(mobile ->
                SingleCallByTtsRequest.builder()
                        .calledNumber(mobile)
                        .ttsCode(templateCode)
                        .ttsParam(paramJson)
                        .build()
        ).forEach(request -> {
            try {
                final CompletableFuture<SingleCallByTtsResponse> response = client.singleCallByTts(request);
                log.info(JSONUtil.toJsonPrettyStr(response.get()));
            } catch (Exception e) {
                log.error("阿里云语音通知发起失败:[{}]", e.getMessage());
            }
        });
    }
}
